/* 
 * Copyright [2018] [Alex/libo(liboware@gmail.com)]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.infodb.config;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.MediaType;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.hyts.infodb.enums.SystemConfiguration.JsonConfiguration;

/** 
 * @author LiBo/Alex
 * @version V1.0 
 */
@Configuration
public class FastJsonConfiguration {
        
    @Primary
    @Bean
    public HttpMessageConverters fastJsonMessageConverters() {
        //fastjson定义转换器
        FastJsonHttpMessageConverter fastJsonHttpMessageConverters = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setDateFormat(JsonConfiguration.JSON_DATE_FORMAT.getValue());
        fastJsonConfig.setCharset(Charset.forName(JsonConfiguration.JSON_DATA_ENCODE.getValue()));
        List<SerializerFeature> serializerFeatures = new ArrayList<>();
        serializerFeatures.add(SerializerFeature.WriteNonStringValueAsString);
        //serializerFeatures.add(SerializerFeature.WriteNullNumberAsZero);
        if("pretty".equalsIgnoreCase(JsonConfiguration.JSON_DATA_ENCODE.getValue())) {
            serializerFeatures.add(SerializerFeature.PrettyFormat);
        }
        serializerFeatures.add(SerializerFeature.WriteNullListAsEmpty);
        //解决乱码问题
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastJsonHttpMessageConverters.setSupportedMediaTypes(supportedMediaTypes);
        fastJsonHttpMessageConverters.setFastJsonConfig(fastJsonConfig);
        fastJsonConfig.setSerializerFeatures(serializerFeatures.toArray(new SerializerFeature[serializerFeatures.size()]));
        return new HttpMessageConverters(fastJsonHttpMessageConverters);
    }
}
